﻿//This C# code file was released under the Ms-PL license
//http://www.opensource.org/licenses/ms-pl.html
//This script was originally intended for use with Microsoft Dynamics AX
//and maintained and distributed as a project on CodePlex
//http://dynamicsaxbuild.codeplex.com

using System;
using System.Collections.Generic;
using System.Text;
using System.Activities;
using System.IO;
using System.Text.RegularExpressions;
using Microsoft.TeamFoundation.Build.Client;
using Microsoft.TeamFoundation.Build.Workflow.Activities;
using System.Linq;

namespace AXTFSBuildLibrary
{
    [BuildActivity(HostEnvironmentOption.All)]
    public class LabelClean : CodeActivity
    {
        [RequiredArgument]
        public InArgument<string> ServerLabelFilePath { get; set; }

        [RequiredArgument]
        public InArgument<DynamicsAXVersion> Version { get; set; }

        public InArgument<string> ServerName { get; set; }

        private string[] labelFileFilters = { "*.ald", "*.alc", "*.ali" };

        protected override void Execute(CodeActivityContext context)
        {
            DynamicsAXVersion version = Version.Get(context);
            if (version != DynamicsAXVersion.AX2012)
            {
                throw new Exception("Label cleanup step activated for unsupported Dynamics AX version");
            }

            string serverLabelFilePath = ServerLabelFilePath.Get(context);

            if (String.IsNullOrWhiteSpace(serverLabelFilePath))
            {
                throw new Exception("Label file path not specified");
            }

            if (!Directory.Exists(serverLabelFilePath))   // TODO - Handle non-local server?
            {
                throw new Exception("Cannot access server label file path: " + serverLabelFilePath);
            }

            foreach (string fileName in labelFileFilters.AsParallel().SelectMany(searchPattern => Directory.EnumerateFiles(serverLabelFilePath, searchPattern)))
            {
                context.TrackBuildMessage(String.Format("Attempting to delete {0}", fileName), BuildMessageImportance.Normal);
                // An exception only from deleting the label file is not severe enough
                // to fail the build step.  It must be logged with the proper importance though.
                try
                {
                    File.Delete(fileName);
                }
                catch (UnauthorizedAccessException ex)
                {
                    context.TrackBuildMessage(String.Format("Access error deleting {0}: {1}", fileName, ex.Message), BuildMessageImportance.High);
                }
                catch (Exception ex)
                {
                    context.TrackBuildMessage(String.Format("General error deleting {0}: {1}", fileName, ex.Message), BuildMessageImportance.High);
                }
            }
        }
    }
}
